package services

import (
	"cloud-navigation/utils"
	"encoding/json"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
)

type Csdn struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
	Data struct {
		Address string `json:"address"`
		IP      string `json:"ip"`
	}
}

// 获取ip属地
func GetIPAddress(c *gin.Context) string {
	ip := utils.GetRealIP(c)
	if ip == "" {
		return ""
	}
	resp, err := http.Get("https://searchplugin.csdn.net/api/v1/ip/get?ip=" + ip)
	if err != nil {
		return ""
	}
	defer resp.Body.Close()
	if resp.StatusCode != 200 {
		return ""
	}

	var csdn Csdn
	err = json.NewDecoder(resp.Body).Decode(&csdn)
	if err != nil {
		return ""
	}
	arr := strings.Split(csdn.Data.Address, " ")
	return strings.Join(arr[:len(arr)-2], "")
}
